<template>
  <el-container style="height: 100%">
    <el-header>
      <h1>Neusoft&nbsp;&nbsp;东软体检报告管理系统</h1>
      <p>
        医生：{{ realName }}
      </p>
    </el-header>
    <el-container>
      <el-aside width="260px">
        <h4>体检用户查询</h4>
        <el-form ref="formRef" :model="selectForm" label-width="auto">
          <el-form-item label="手机号码">
            <el-input v-model="selectForm.phone" placeholder="手机号码"></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="selectForm.realName" placeholder="姓名"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="selectForm.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="套餐类型">
            <el-select v-model="selectForm.smId" placeholder="套餐类型">
              <el-option v-for="setmeal in setmealArr" :key="setmeal.smId" :label="setmeal.name"
                :value="setmeal.smId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="体检日期">
            <el-date-picker v-model="selectForm.orderDate" type="date" placeholder="体检日期" style="width: 100%"
              format="YYYY/MM/DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
          <el-form-item label="是否归档">
            <el-radio-group v-model="selectForm.state">
              <el-radio border label="1">未归档</el-radio>
              <el-radio border label="2">已归档</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="doSelect">查询</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-aside>
      <el-main>
        <el-table :data="ordersPageResponseDto.list" style="width: 100%">
          <el-table-column prop="orderId" label="预约编号" width="120" />
          <el-table-column prop="phone" label="手机号码" width="140" />
          <el-table-column prop="realName" label="真实姓名" width="120" />
          <el-table-column label="性别" width="60">
            <template #default="scope">
              <span>{{ scope.row.sex == 1 ? "男" : "女" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="setmealName" label="套餐类型" />
          <el-table-column prop="hospitalName" label="体检医院" width="220" />
          <el-table-column prop="orderDate" label="体检日期" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="text" size="small" @click="ciReport(scope.row)">{{ scope.row.state == 1 ? '编辑体检报告' :
                '查看体检报告' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="prev, pager, next, total" :total="ordersPageResponseDto.totalRow"
          :page-size="ordersPageResponseDto.maxPageNum" style="margin-top: 20px" @current-change="currentChange">
        </el-pagination>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { computed, onBeforeMount, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from '@/plugins/axios';

let router = useRouter();
// 定义表单数据
const selectForm = ref({
  phone: '',
  realName: '',
  sex: '',
  smId: '',
  orderDate: '',
  state: ''
});

const doctor = ref({});
const realName = computed(() => doctor.value.realname);

onBeforeMount(() => {
  const doctorData = sessionStorage.getItem('doctor');
  if (doctorData) {
    try {
      doctor.value = JSON.parse(doctorData);
      console.log(doctor.value.realname);
    } catch (e) {
      console.error('Failed to parse doctor data:', e);
    }
  } else {
    console.error('No doctor data found in sessionStorage');
  };
  // 加载前调用查询函数
  doSelect();
});


// 定义套餐列表
const setmealArr = ref([]);

// 定义表格数据
const ordersPageResponseDto = ref({
  list: [],
  totalRow: 0,
  maxPageNum: 10
});

// 获取套餐列表的函数
const fetchSetmealList = async () => {
  // 这里应该调用后端API获取套餐列表
  // setmealArr.value = await someApiCall();
  // 模拟数据
  setmealArr.value = [
    { smId: 1, name: '男士-基础套餐' },
    { smId: 2, name: '男士-肾病检查' },
    { smId: 3, name: '男士-肝病检查' },
    { smId: 4, name: '女士-基础套餐' },
    { smId: 5, name: '女士-肾病检查' },
    { smId: 6, name: '女士-肝病检查' },
  ];
};

// 查询函数
const doSelect = async () => {
  try {
    // 构建请求参数对象
    let params = {};
    for (let key in selectForm.value) {
      if (selectForm.value[key] !== '') {
        params[key] = selectForm.value[key];
      }
    }

    // 构建查询字符串
    let queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');

    // 调用后端API进行查询
    const response = await axios.post(`http://localhost:9000/user/getUserOrder?${queryString}`);

    if (response.data.code == 200) {
      // 解析并处理数据
      const userOrderVOS = response.data.data; // 假设response.data就是UserOrderVO的列表

      // 赋值给ordersPageResponseDto的list属性
      ordersPageResponseDto.value.list = userOrderVOS;
    } else {
      alert(response.data.message);
    }
  } catch (error) {
    alert(error);
  }
};

// 重置函数
const reset = () => {
  selectForm.value = {
    phone: '',
    realName: '',
    sex: '',
    smId: '',
    orderDate: '',
    state: ''
  };
  // 重新调用查询函数
  doSelect();
};

// 分页改变时的回调
const currentChange = (currentPage) => {
  // 在这里处理分页逻辑，重新加载数据
  // fetchOrders(selectForm.value, currentPage);
};

// 编辑或查看体检报告的函数
// 未归档的编辑，已归档的查看
const ciReport = (row) => {
  if (row.state == 1) {
    ElMessage.info('开始编辑体检报告');
  } else {
    ElMessage.info('查看体检报告');
  }
  // 这里应该跳转到相应的页面或打开模态框，并传入当前行的数据
  router.push({ path: '/ordersContent', query: { orderId: row.orderId,
    state: row.state,
    phone: row.phone,
    realName: row.realName,
    sex: row.sex,
    setmealName: row.setmealName,
    hospitalName: row.hospitalName,
    orderDate: row.orderDate,
   } });
};

// 初始化组件时加载套餐列表
fetchSetmealList();
</script>


<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;

  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #1c51a3;
}

.el-header h1 {
  font-size: 22px;
  font-weight: 700;
}

.el-header p {
  font-size: 16px;
}

.el-aside {
  background-color: #d3dce6;
  box-sizing: border-box;
  padding: 20px;
}

.el-aside h4 {
  color: #555;
  margin-bottom: 20px;
}

.el-main {
  background-color: #e9eef3;
}
</style>